package com.sky.controller.user;

import com.sky.entity.Dish;
import com.sky.mapper.DishMapper;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;



    @Autowired
    private RedisTemplate redisTemplate; //用于缓存菜品信息

    @GetMapping("/list")
    public Result<List<DishVO>> list(Long categoryId){

        //设置redis的key，使用分类dish_id作为key
        String key = "dish_" + categoryId;

        //查询是否存在
        List<DishVO> listR = (List<DishVO>) redisTemplate.opsForValue().get(key);

        if(listR != null && listR.size() > 0){
            //存在，直接返回
            log.info("redis存在：{}",key);
            return Result.success(listR);
        }
        //如果不存在则查询数据库，并将数据存放进入redis中
        log.info("根据分类id查询菜品：{}",categoryId);
        //查询菜品信息
        List<DishVO> list = dishService.userList(categoryId);
        //将数据存入redis中
        redisTemplate.opsForValue().set(key,list);
        log.info("将数据存入Redis缓存，key: {}", key);
        return Result.success(list);
    }
}
